import { ref } from 'vue';
// layout组件相关配置
import { defineStore } from "pinia";
import {
  getCategory1API,
  getCategory2API,
  getCategory3API,
  getAttrInfoAPI,
  deleteAttrInfoAPI,
  saveAttrInfoAPI
} from '@api/product/attr/index.ts'
import type {
  formValueType,
  categoryListType,
  categoryItemType,
  attrItemType
} from '@api/product/attr/type.ts'
import { ElMessage } from 'element-plus'

export const useCategoryStore = defineStore('category', () => {
  const form = ref<formValueType>({
    category1Id: '',
    category2Id: '',
    category3Id: '',
  })

  const category1List = ref<categoryItemType[]>([])
  const category2List = ref<categoryItemType[]>([])
  const category3List = ref<categoryItemType[]>([])

  // 初始化获取一级分类数据
  const getCategory1Fn = async () => {
    const res: categoryListType = await getCategory1API()
    if (res.code === 200) {
      category1List.value = res.data
    }
  }

  // 选择一级分类后获取二级分类数据
  const getCategory2Fn = async (id: number) => {
    form.value.category2Id = ''
    form.value.category3Id = ''
    category3List.value = []
    attrList.value = []
    const res: categoryListType = await getCategory2API(id)
    if (res.code === 200) {
      category2List.value = res.data
    }
  }

  // 选择二级分类后获取三级分类数据
  const getCategory3Fn = async (id: number) => {
    form.value.category3Id = ''
    attrList.value = []
    const res: categoryListType = await getCategory3API(id)
    if (res.code === 200) {
      category3List.value = res.data
    }
  }

  // 选择三级分类后获取属性与属性值列表
  const loading = ref(false)
  const attrList = ref<attrItemType[]>([])
  const getAttrInfoFn = async () => {
    loading.value = true
    const res = await getAttrInfoAPI(form.value)
    attrList.value = res.data
    loading.value = false
  }

  // 删除属性与属性值
  const deleteAttrInfoFn = async (id: number) => {
    const res = await deleteAttrInfoAPI(id)
    console.log(res);
    if(res.code === 200) {
      getAttrInfoFn()
    }
  }

  // 属性数据
  const attrParams = ref<attrItemType>({
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3
  })

  const saveAttrInfoFn = async () => {
    const res = await saveAttrInfoAPI(attrParams.value)
    if(res.code === 200) {
      ElMessage.success(res.message)
      getAttrInfoFn()
      return 'ok'
    } else {
      ElMessage.error(res.message)
      return Promise.reject(new Error(res.message))
    }
  }

  return {
    form, attrList, attrParams, loading, category1List, category2List, category3List, getCategory1Fn, getCategory2Fn, getCategory3Fn, getAttrInfoFn, deleteAttrInfoFn, saveAttrInfoFn
  }
})